package com.zbmsg.user.impl;

import org.springframework.stereotype.Service;

import com.zbmsg.server.Global;
import com.zbmsg.user.bean.User;
import com.zbmsg.user.service.IUserService;
import com.zbmsg.utils.id.IdWorker;

import io.netty.channel.Channel;

@Service("userService")
public class IUserServiceImpl implements IUserService {

	public User add(String name) throws Exception {
		User user = new User();
		user.setName(name);
		user.setId(String.valueOf(IdWorker.getInstance().nextId()));
		Global.users.put(user.getId(), user);
		return user;
		// 如果出现重复数据影响内存那么就想办法开个定时任务 定时处理失效的连接。
		// 20180826 拿着连接判断连接是否失效
	}

	@Override
	public User setChannel(String userId, Channel channel) throws Exception {
		User user = Global.users.get(userId);
		if (user == null) {
			return null;
		}
		user.setChannel(channel);
		Global.users.put(userId, user);
		return user;
	}

	@Override
	public void remove(String userId) throws Exception {
		User user = Global.users.get(userId);
		if (user != null) {
			user.getChannel().close();
			Global.users.remove(userId);
		}
	}

	@Override
	public User getUserByChannel(Channel channel) throws Exception {
		User user = null;
		for (User u : Global.users.values()) {
			if (u.getChannel().equals(channel)) {// 如果无效则通过id的方式判断
				user = u;
				break;
			}
		}
		return user;
	}

	@Override
	public User updateUser(User user) throws Exception {
		User oldUser = Global.users.get(user.getId());
		if (oldUser == null) {
			return null;
		}
		Global.users.remove(oldUser.getId());
		Global.users.put(user.getId(), user);
		return user;
	}

	@Override
	public User getUserByUserId(String userId) throws Exception {
		return Global.users.get(userId);
	}
}
